/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.handlers;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.ChangeBoundsRequest;

import com.cea.papyrus.core.utils.LookForElement;
import com.cea.papyrus.diagraminterchange2.di2.Diagram;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;

/**
 * @author frankd@ifi.uio.no
 */
public class InteractionAddCFHandler {

    public final EditPolicy hostPolicy;

    public InteractionAddCFHandler(final EditPolicy hostPolicy) {
        this.hostPolicy = hostPolicy;
    }

    @SuppressWarnings("unchecked")
    public Command[] getAddCommands(GraphicalEditPart cfragmentEP, Rectangle r) {
        // The bounds are expected to be in diagram coordinates

        // We don't add the CF as a child of the interaction frame, but
        // rather move it so that it appears to be inside.

        GraphNode cfragmentView = (GraphNode) cfragmentEP.getModel();
        Diagram diagram = LookForElement.getDiagram(cfragmentView);

        // Construct a move request and direct it to the diagram editpart
        Rectangle currentBounds =
                new Rectangle(cfragmentView.getPosition(), cfragmentView.getSize());

        ChangeBoundsRequest req = new ChangeBoundsRequest();
        req.setType(RequestConstants.REQ_MOVE_CHILDREN);
        req.setEditParts(cfragmentEP);
        req.setLocation(r.getLocation());
        req.setMoveDelta(new Point(r.x - currentBounds.x, r.y - currentBounds.y));

        GraphicalEditPart diagramEP =
                (GraphicalEditPart) hostPolicy.getHost().getViewer().getEditPartRegistry().get(
                        diagram);
        return new Command[] {
            diagramEP.getCommand(req)
        };
    }
}
